package com.jichangxiu.framework.security.handler;

import cn.hutool.json.JSONUtil;
import com.jichangxiu.common.entity.bo.Result;
import com.jichangxiu.common.properties.JcxProperties;
import com.jichangxiu.common.utils.CacheUtils;
import com.jichangxiu.common.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * LogoutSuccessHandler:
 *
 * @author Jcx
 * @create 2023-04-04 13:38
 */
@Slf4j
@Component
public class LogoutHandler implements LogoutSuccessHandler {

    @Resource
    private JcxProperties jcxProperties;

    @Resource
    private TokenUtils tokenUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 这里拿到的是前端传来的短令牌真正的 JWT 载荷需要去 Redis 中取
        // 清空内存缓存
        CacheUtils.remove(tokenUtils.getJti(httpServletRequest));
        // 清空 redis 缓存
        tokenUtils.logout(httpServletRequest);
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(httpServletRequest, httpServletResponse, authentication);
        }
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        if (jcxProperties.getAuthProperties().getWriteJtiToHeader()) {
            httpServletResponse.setHeader(jcxProperties.getAuthProperties().getAuthHeaderKey(), "");
        }
        Result<String> result = Result.ok("操作成功", "退出登录成功");
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }

}
